package cn.frh.org.controller;

import cn.frh.basic.util.AjaxResult;
import cn.frh.org.domain.Department;
import cn.frh.org.query.DepartmentQuery;
import cn.frh.org.service.IDepartmentService;
import cn.frh.basic.util.PageList;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/dept")
@Api(tags = "部门接口",description = "部门接口详细描述")
public class DepartmentController {

    @Autowired
    private IDepartmentService departmentService;

    /**
     * 查询一条数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Department findById(@PathVariable("id") Long id){
        return departmentService.queryById(id);
    }
    //查询所有数据
    @GetMapping("/list")
    public List<Department> findAll(){
        return departmentService.queryAll();
    }

    @PostMapping("/page")
    public PageList<Department> queryPage(@RequestBody DepartmentQuery query,HttpServletRequest request){
        System.out.println(request.getHeader("token"));
        return departmentService.queryPage(query);
    }
    @DeleteMapping("/{id}")
    public AjaxResult removeByUd(@PathVariable("id") Long id){
        try {
            departmentService.remove(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("骚瑞~操作失败！");
        }
    }

    @PostMapping("/save")
    @ApiOperation(value = "部门添加或修改",notes = "如果有id就是修改否则就是添加")
    public AjaxResult addOrUpdate(@RequestBody Department department){
        try {
            if (department.getId() == null){
                departmentService.add(department);

            }else {
                departmentService.update(department);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("骚瑞 操作失败");
        }
    }

    @PatchMapping
    public AjaxResult batchRemove(@RequestBody List<Long> ids){
        try {
            departmentService.batchRemove(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("骚瑞~操作失败！");
        }
    }
    @PostMapping("/tree")
    public List<Department> findOneAndTwoLevelTree(){
        return departmentService.findOneAndTwoLevelTree();
    }
}
